import AbstractResponse from '@/abstract/response';
import {
  auth,
  body,
  catchError,
  Controller,
  get,
  post,
} from '@/decorator/controller';
import { jwtSign } from '@/middleware/authorization';
import { UnitRepository, UserEntity } from '@/models';
import { models } from '@/mysql/new-index';
import { crypted } from '@/utils/crypto';
import buildResponseSchema from '@/utils/swagger';
import { ParameterizedContext } from 'koa';
import {
  body as sBody,
  request, // body中的参数
  responses,
  summary,
  tags,
} from 'koa-swagger-decorator';

const tag = tags(['User']);
const { User } = models;
@Controller('/user')
class UserController extends AbstractResponse {
  constructor() {
    super();
  }

  @request('post', '/user/login')
  @summary('用户登录')
  @tag
  @sBody({
    nickname: { type: 'string', required: false },
    password: { type: 'string', required: false },
  })
  @responses({
    200: {
      description: 'success',
      schema: buildResponseSchema(UserEntity, 'object'),
    },
    400: { description: 'error' },
  })
  @post()
  @body({
    nickname: {
      required: true,
    },
    password: {
      required: true,
    },
  })
  @catchError()
  async login(ctx: ParameterizedContext) {
    const params = ctx.request.body;
    const res = await User.findOne({
      where: {
        nickname: params.nickname,
        password: crypted.md5(params.password),
      },
    });

    if (res) {
      await res.update({
        loginStatus: true as any,
      });
      const userInfo: any = res.toJSON();
      userInfo['token'] = jwtSign({ id: userInfo.id });

      super.success(ctx, userInfo, '登录成功');
    } else {
      super.error(ctx, '用户名或者密码出错！');
    }
  }
  // 分隔符
  @request('post', '/user/registry')
  @summary('用户注册')
  @tag
  @sBody((UserEntity as any).swaggerDocument)
  @responses({
    200: {
      description: 'success',
      schema: buildResponseSchema(UserEntity, 'object'),
    },
    400: { description: 'error' },
  })
  @post()
  @body({
    nickname: {
      required: false,
    },
    password: {
      required: false,
    },
  })
  @catchError()
  async registry(ctx: ParameterizedContext) {
    const params = ctx.request.body;
    const ip = ctx.ip;

    const err = await User.findOne({
      where: { nickname: params.nickname, password: params.password },
    });

    if (err) {
      super.error(ctx, '用户名已存在');
      return;
    }

    const res = await User.create({
      nickname: params.nickname,
      password: crypted.md5(params.password),
      email: params.email,
      phone: params.phone,
      ip: ip,
    });

    super.success(ctx, res);
  }

  @get()
  @auth()
  async getCurrentUserInfo(ctx: ParameterizedContext) {
    // console.log('getCurrentUserInfo', ctx);
    const userInfo = await User.findByPk(ctx.jwtAuthInfo.id);
    super.success(ctx, userInfo);
  }

  // 分隔符
  @request('get', '/user/loginStatus')
  @summary('登陆状态')
  @tag
  @sBody({
    nickname: { type: 'string', required: false },
    password: { type: 'string', required: false },
  })
  @responses({
    200: {
      description: 'success',
      schema: buildResponseSchema(UserEntity, 'object'),
    },
    400: { description: 'error' },
  })
  @post()
  @body({
    nickname: {
      required: true,
    },
    password: {
      required: true,
    },
  })
  @catchError()
  async loginStatus(ctx: ParameterizedContext) {
    const params = ctx.request.body;
    const res = await User.findOne({
      where: {
        nickname: params.nickname,
        password: crypted.md5(params.password),
      },
    });
    if (res) {
      super.success(ctx, res, '获取登陆状态成功！');
    } else {
      super.error(ctx, '获取登陆状态失败！');
    }
  }

  @request('get', '/user/loginByIp')
  @summary('使用ip登录')
  @tag
  @sBody({})
  @responses({
    200: {
      description: 'success',
      schema: buildResponseSchema(UserEntity, 'object'),
    },
    400: { description: 'error' },
  })
  @get()
  @body({})
  @catchError()
  async loginByIp(ctx: ParameterizedContext) {
    const [user, created] = await User.findOrCreate({
      where: { ip: ctx.ip },
      defaults: {
        nickname: jwtSign({ id: ctx.ip }).substr(0, 10),
        password: crypted.md5('a123456'),
        ip: ctx.ip,
      },
    });

    // if (created) {
    if (user) {
      await user.update({
        loginStatus: true as any,
      });
      const userInfo: any = user.toJSON();
      userInfo['token'] = jwtSign({ id: userInfo.id });
      super.success(ctx, userInfo, '登陆成功');
    } else {
      super.error(ctx, '登陆失败！');
    }
  }
}

export default UserController;
